# Maintainer: Shiwei Wang <wsw0108@qq.com>

_realname=tree-sitter
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-lib${_realname}")
pkgver=0.25.4
pkgrel=2
pkgdesc="An incremental parsing system for programming tools (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://tree-sitter.github.io/"
msys2_repository_url="https://github.com/tree-sitter/tree-sitter"
msys2_references=(
  'archlinux: tree-sitter'
  'purl: pkg:cargo/tree-sitter'
)
license=('spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-libwasmtime")
checkdepends=('git')
source=("https://github.com/tree-sitter/tree-sitter/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('87eadc505905c70a692917c821958a819903f808f8d244068b1d273a033dc728')
noextract=("${_realname}-${pkgver}.tar.gz")

prepare() {
  tar -xzf "${_realname}-${pkgver}.tar.gz" || true
  cd "${_realname}-${pkgver}"

  cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  export RUSTFLAGS="${RUSTFLAGS/+crt-static/-crt-static}"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DTREE_SITTER_FEATURE_WASM=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -S "${_realname}-${pkgver}/lib" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"

  cargo build \
    --frozen \
    --profile optimize \
    --features wasm \
    --manifest-path "${_realname}-${pkgver}/Cargo.toml"
}

package_tree-sitter() {
  pkgdesc+=' (CLI)'
  depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")

  install -Dm755 "${_realname}-${pkgver}/target/optimize/tree-sitter.exe" "${pkgdir}${MINGW_PREFIX}/bin/tree-sitter.exe"
  install -Dm644 "${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}

package_libtree-sitter() {
  pkgdesc+=' (C library)'
  depends=("${MINGW_PACKAGE_PREFIX}-libwasmtime")

  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"
  install -Dm644 "${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/lib${_realname}/LICENSE"
}

# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
